﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SHack.Helper;
using System.Net;
using System.IO;
using SHack.WorkSpace;
using SMDS;

namespace SHack
{
    public partial class FrmMain : Form
    {
        private HttpScan httpScan = new HttpScan();
        private PingScan pingScan = new PingScan();
        private PortScan portScan = new PortScan();
        private WebScan webScan = new WebScan();
        private VarFile varHttp = new VarFile();

        private SortedList<string, int> slPortIndex = new SortedList<string, int>();
        private object objPortLocker = new object();

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            webScan.ScanCompleteEvent+=new BaseScan.ScanCompleteHandler(webScan_ScanCompleteEvent);
            webScan.ScanFoundUrlEvent += new WebScan.ScanFoundUrlHandler(WebScan_ScanFoundUrlEvent);
            webScan.ScaningEvent += new WebScan.ScaningHandler(WebScan_ScaningEvent);

            pingScan.ScanFoundPingEvent+=new PingScan.ScanFoundPingHandler(PingScan_ScanFoundPingEvent);
            pingScan.ScanCompleteEvent+=new BaseScan.ScanCompleteHandler(PingScan_ScanCompleteEvent);
            

            portScan.ScanFoundPortEvent += new PortScan.ScanFoundPortHandler(PortScan_ScanFoundPortEvent);
            portScan.ScanCompleteEvent+=new BaseScan.ScanCompleteHandler(PortScan_ScanCompleteEvent);

            portScan.ScaningTestPassEvent+=new PortScan.ScaningTestPassHandler(PortScan_ScaningTestPassEvent);
            httpScan.ScanCompleteEvent+=new BaseScan.ScanCompleteHandler(HttpScan_ScanCompleteEvent);
            httpScan.FoundVarEvent+=new HttpScan.FoundVarHandler(HttpScan_FoundVarEvent);

            Web_Init();
            Ping_Init();
            Port_Init();
            Http_Init();
            Tool_Init();

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {

            Config.Save();

            Application.ExitThread();
            Application.Exit();
            Environment.Exit(0);
        }


        #region WEB
        private void Web_Init()
        {
            for (int i = 1; i <= 100; i++)
            {
                cboxWebThread.Items.Add(i.ToString());
            }
           

            for (int i = 100; i <= 10000; i+=100)
            {
                cboxWebTimeout.Items.Add(i);
            }

            Config.Get(txtWebSite);
            Config.Get(cboxWebThread, "30");
            Config.Get(cboxWebTimeout, "2000");

            Config.Get(chkWebDir,"True");
            Config.Get(chkWebPhp);
            Config.Get(chkWebAspx);
            Config.Get(chkWebAsp);
            Config.Get(chkWebJsp);
            Config.Get(chkWebMdb);
            Config.Get(chkWebFile, "True");
            Config.Get(chkWebHtml, "True");

            webScan.Load(Config.URLFile);

            if (webScan.FileCount ==  0)
            {
                labState.Text = "未能成功加载URL路径库，请检查【URL.txt】是否存在！";
            }
            else
            {
                chkWebDir.Text = "目录(" + webScan.DirCount + ")";
                chkWebMdb.Text = "MDB(" + webScan.MdbCount + ")";
                chkWebPhp.Text = "PHP(" + webScan.ScriptCount + ")";
                chkWebAsp.Text = "ASP(" + webScan.ScriptCount + ")";
                chkWebAspx.Text = "ASPX(" + webScan.ScriptCount + ")";
                chkWebJsp.Text = "JSP(" + webScan.ScriptCount + ")";
                chkWebHtml.Text = "HTML(" + webScan.ScriptCount + ")";
                chkWebFile.Text = "RAR、ZIP、TXT(" + webScan.FileCount + ")";

            }
        }

        private void webScan_ScanCompleteEvent()
        {
            this.BeginInvoke((Action)delegate
            {
                timerWeb.Enabled = false;
                btnWebStart.Text = "开始扫描";
                pbar.Value = pbar.Maximum;
                labExpect.Text = "共计耗时：" + webScan.SpandTime;
                labSpeed.Text = "平均速度：" + webScan.AvgSpeed.ToString() + "/s";
                labState.Text = "扫描结束，共检测到" + webScan.SuccCount.ToString() + "个结果！";
                MessageBox.Show("扫描结束，共检测到" + webScan.SuccCount.ToString() + "个结果！", "扫描完成");
            });
        }

        private void btnWebStart_Click(object sender, EventArgs e)
        {
            if (btnWebStart.Text == "停止扫描")
            {
                webScan.Stop();
                labState.Text = "扫描结束，共检测到" + lvWebResult.Items.Count.ToString() + "个页面！";
                btnWebStart.Text = "开始扫描";
                timerWeb.Enabled = false;
            }
            else
            {
                string url = txtWebSite.Text.Trim();
                if (url.Length == 0)
                    return;

                bool ishttps = url.ToLower().Contains("https://");

                if (url.ToLower().StartsWith("http://"))
                    url = url.Substring(7, url.Length - 7);
                else if (url.ToLower().StartsWith("https://"))
                    url = url.Substring(8, url.Length - 8);

                int lastSplit = url.LastIndexOf("/");
                int lastPoint = url.LastIndexOf(".");
                if (lastSplit > 0 && lastPoint > lastSplit)
                    url = url.Substring(0, lastSplit);

                if (url.Substring(url.Length - 1, 1) == "/")
                    url = url.Substring(0, url.Length - 1);


                if (ishttps)
                    url = "https://" + url;
                else
                    url = "http://" + url;


                if (lvWebResult.Items.Count > 0)
                {
                    if (MessageBox.Show("是否清空搜索结果？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        lvWebResult.Items.Clear();
                }

                int threadCount = Convert.ToInt32(cboxWebThread.Text);
                int timeOut = Convert.ToInt32(cboxWebTimeout.Text);
                List<string> ltExts = new List<string>();

                if (chkWebPhp.Checked)
                {
                    ltExts.Add("do");
                    ltExts.Add("php");
                }
                if (chkWebJsp.Checked)
                    ltExts.Add("jsp");

                if (chkWebAspx.Checked)
                    ltExts.Add("aspx");

                if (chkWebAsp.Checked)
                    ltExts.Add("asp");

                if (chkWebHtml.Checked)
                {
                    ltExts.Add("html");
                    ltExts.Add("htm");
                }


                int totalCount = webScan.Start(url, threadCount, timeOut, chkWebDir.Checked, chkWebMdb.Checked, chkWebFile.Checked, ltExts.ToArray());

                if (totalCount == -1)
                {
                    MessageBox.Show(webScan.Error, "开启失败");
                }
                pbar.Value = 0;
                pbar.Maximum = totalCount;

                btnWebStart.Text = "停止扫描";
                timerWeb.Enabled = true;
                labTotalTarget.Text = "检测总数：" +webScan.TotalCount.ToString();
            }
        }

        private void WebScan_ScaningEvent(string scanUrl)
        {
            if (webScan.PassCount % 2 == 0)
            {
                this.BeginInvoke((Action)delegate
                {
                    labState.Text = scanUrl;
                    Application.DoEvents();
                });
            }
        }

        private void WebScan_ScanFoundUrlEvent(string foundUrl,string retCode)
        {
            
            lvWebResult.BeginInvoke((Action)delegate {
                try
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = (lvWebResult.Items.Count + 1).ToString();
                    lvi.SubItems.Add(foundUrl);
                    lvi.SubItems.Add(retCode);
                    lvWebResult.Items.Add(lvi);
                    //lvWebResult.Items[lvWebResult.Items.Count - 1].EnsureVisible();
                    Application.DoEvents();
                }
                catch { }

            });
        }

        private void timerWeb_Tick(object sender, EventArgs e)
        {
            pbar.Value = webScan.PassCount;
            labSpeed.Text = "扫描速度：" + webScan.Speed.ToString() + "/s";
            labExpect.Text = "剩余时间：" + webScan.ExpectComplete;
            //labStatus.Text = WebScan.PassCount.ToString() + "/" + WebScan.TotalCount.ToString();
        }

        private void lvWebResult_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lvWebResult.SelectedItems.Count == 0)
                return;

            new FrmWebLook(lvWebResult.SelectedItems[0].SubItems[1].Text).Show();
        }

        private void btnWebClear_Click(object sender, EventArgs e)
        {
            lvWebResult.Items.Clear();
        }

        private void chkWebTotal_CheckedChanged(object sender, EventArgs e)
        {
            chkWebDir.Checked = chkWebTotal.Checked;
            chkWebPhp.Checked = chkWebTotal.Checked;
            chkWebAspx.Checked = chkWebTotal.Checked;
            chkWebAsp.Checked = chkWebTotal.Checked;
            chkWebHtml.Checked = chkWebTotal.Checked;
            chkWebMdb.Checked = chkWebTotal.Checked;
            chkWebJsp.Checked = chkWebTotal.Checked;
            chkWebFile.Checked = chkWebTotal.Checked;
        }

        private void btnWebSave_Click(object sender, EventArgs e)
        {
            if (webScan.Save())
            {
                MessageBox.Show("已经去重数据并优化完成，当前共有" + webScan.TotalDataCount+"条数据。", "完成");
            }
            else
            {
                MessageBox.Show(webScan.Error, "优化失败");
            }
        }


        #endregion

        #region PING
        private void Ping_Init()
        {
            for (int i = 1; i <= 100; i++)
            {
                cboxPingThread.Items.Add(i.ToString());
            }

    


            Config.Get(txtPingStart);
            Config.Get(txtPingEnd);
            Config.Get(cboxPingThread, "20");

        }

        private void btmPingStart_Click(object sender, EventArgs e)
        {
            pingScan.Stop();

            if (btnPingStart.Text == "停止扫描")
            {
                timerPort.Enabled = false;
                btnPingStart.Text = "开始扫描";
                labState.Text = "扫描结束，共检测到" + lvPortResult.Items.Count.ToString() + "个端口！";
            }
            else
            {
                string startIp = txtPingStart.Text.Trim();
                string endIp = txtPingEnd.Text.Trim();

                int threadCount = Convert.ToInt32(cboxPingThread.Text);

                if (lvPingResult.Items.Count > 0)
                {
                    if (MessageBox.Show("是否清空搜索结果？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        lvPingResult.Items.Clear();
                }

                pbar.Value = 0;
                pbar.Maximum = 0;
                if (!pingScan.Start( threadCount, startIp, endIp))
                {
                    labState.Text = pingScan.Error;
                    MessageBox.Show(pingScan.Error, "开启失败");
                    return;
                }

                pbar.Maximum = pingScan.TotalCount;
                labState.Text = "正在扫描...";
                timerPing.Enabled = true;
                btnPingStart.Text = "停止扫描";

                labTotalTarget.Text = "检测总数：" + pingScan.TotalCount.ToString();
            }

        }

        private void PingScan_ScanFoundPingEvent(string ip, int mills)
        {
            lvPingResult.BeginInvoke((Action)delegate
            {
                try
                {

                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = (lvPingResult.Items.Count + 1).ToString();
                    lvi.SubItems.Add(ip);
                    lvi.SubItems.Add(mills.ToString() +"ms");


                    lvPingResult.Items.Add(lvi);


                    //lvPortResult.Items[lvPortResult.Items.Count - 1].EnsureVisible();
                    labState.Text = "发现主机：" + ip;
                    Application.DoEvents();
                }
                catch { }

            });
        }

        private void PingScan_ScanCompleteEvent()
        {
            try
            {
                this.BeginInvoke((Action)delegate
                {
                    timerPort.Enabled = false;
                    btnPingStart.Text = "开始扫描";
                    pbar.Value = pbar.Maximum;
                    labExpect.Text = "共计耗时：" + pingScan.SpandTime;
                    labSpeed.Text = "平均速度：" + pingScan.AvgSpeed.ToString() + "/s";
                    labState.Text = "扫描结束，共检测到" + pingScan.SuccCount.ToString() + "个结果！";
                    MessageBox.Show("扫描结束，共检测到" + pingScan.SuccCount.ToString() + "个结果！", "扫描完成");
                });
            }
            catch { }
        }

        private void btnPingClear_Click(object sender, EventArgs e)
        {
            lvPingResult.Items.Clear();
        }

        private void timerPing_Tick(object sender, EventArgs e)
        {
            pbar.Value = pingScan.PassCount;
            labSpeed.Text = "扫描速度：" + pingScan.Speed.ToString() + "/s";
            labExpect.Text = "剩余：" + pingScan.ExpectComplete;
        }

        private void txtPingStart_Leave(object sender, EventArgs e)
        {
            if (txtPingEnd.Text.Length == 0 || (txtPingStart.Text.Split('.')[0] != txtPingEnd.Text.Split('.')[0]))
                txtPingEnd.Text = txtPingStart.Text.Trim();
        }

        private void btnPingCopyIP_Click(object sender, EventArgs e)
        {

            ListViewItem lvi = lvPingResult.SelectedItems[0];
            string ip = lvi.SubItems[1].Text;
            ClipboardHelper.SetText(ip);
        }

        private void btnPingCopyTotal_Click(object sender, EventArgs e)
        {
            string ips = "";
            foreach (ListViewItem lvi in lvPingResult.Items)
            {
                ips += lvi.SubItems[1].Text + "\r\n";
            }

            ClipboardHelper.SetText(ips);
        }

        private void btnPingOutputFile_Click(object sender, EventArgs e)
        {
            string ips = "";
            foreach (ListViewItem lvi in lvPingResult.Items)
            {
                ips += lvi.SubItems[1].Text + "\r\n";
            }
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "文本文件(*.txt)|*.txt";
            if (sf.ShowDialog() != DialogResult.OK)
                return;

            try
            {
                File.WriteAllText(sf.FileName, ips);
                MessageBox.Show("保存路径：" + sf.FileName, "保存成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "保存失败");
            }
        }

        private void btnPingScanPort_Click(object sender, EventArgs e)
        {

            ListViewItem lvi = lvPingResult.SelectedItems[0];
            string ip = lvi.SubItems[1].Text;

            txtPortStart.Text = ip;
            txtPortEnd.Text = ip;
            tabMain.SelectedIndex = 2;
        }

        private void lvPingResult_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right || lvPingResult.SelectedItems.Count == 0)
                return;

            menuPing.Show(Cursor.Position);
        }


        #endregion

        #region Port
        private void Port_Init()
        {
            for (int i = 1; i <= 100; i++)
            {
                cboxPortThread.Items.Add(i.ToString());
            }
            
            for (int i = 10; i <= 1000; i+=10)
            {
                cboxPortTimeOut.Items.Add(i.ToString());
            }

            for (int i = 1; i <= 15; i++)
            {
                cboxPortLogin.Items.Add(i.ToString());
            }

            Config.Get(txtPortStart);
            Config.Get(txtPortEnd);
            Config.Get(cboxPortThread,"20");
            Config.Get(cboxPortTimeOut,"200");
            Config.Get(cboxPortLogin, "3");
            Config.Get(txtPortPorts, "21,22,23,25,80,110,135,443,445,1433,1521,3306,3389,8000,8080,8081,8888,9000,9090");

            Config.Get(chkPortGetPassFTP);
            Config.Get(chkPortGetPassSSH);
            Config.Get(chkPortGetPassSMB);
            Config.Get(chkPortGetPassSqlServer);
            Config.Get(chkPortGetPassMysql);
            Config.Get(chkPortGetPassRemote);


            Config.Get(txtPortGetPassFTPUser,"anonymous");
            Config.Get(txtPortGetPassSSHUser,"root");
            Config.Get(txtPortGetPassSMBUser,"administrator");
            Config.Get(txtPortGetPassSqlServerUser,"sa");
            Config.Get(txtPortGetPassMySqlUser,"root");
            Config.Get(txtPortGetPassRemoteUser,"administrator");


            Config.Get(txtPortGetPassFTPPass, "anonymous");
            Config.Get(txtPortGetPassSSHPass, "pass.txt");
            Config.Get(txtPortGetPassSMBPass, "pass.txt");
            Config.Get(txtPortGetPassSqlServerPass, "pass.txt");
            Config.Get(txtPortGetPassMySqlPass, "pass.txt");
            Config.Get(txtPortGetPassRemotePass, "pass.txt");


        }

        private void btnPortPortsNormal_Click(object sender, EventArgs e)
        {
            txtPortPorts.Text = "21,22,23,25,80,110,135,443,445,1433,1521,3306,3389,8000,8080,8081,8888,9000,9090";
        }

        private void btnPortPortsUseal_Click(object sender, EventArgs e)
        {

            txtPortPorts.Text = "21,22,23,25,69,80,81,88,90,110,135,443,445,1000,1158,1343,1432,1433,1434,1435,1520,1521,1522,3300,3304,3305,3306,3307,3308,3333,3389,8000,8001,8080,8081,8888,9000,9090,9098,10000,10086,65530,65531,65532,65533,65534,65535";
        }

        private void btnPortPortsTotal_Click(object sender, EventArgs e)
        {
            txtPortPorts.Text = "1-65535";
        }

        private void btnPortStart_Click(object sender, EventArgs e)
        {
            portScan.Stop();

            if (btnPortStart.Text == "停止扫描")
            {
                timerPort.Enabled = false;
                btnPortStart.Text = "开始扫描";
                labState.Text = "扫描结束，共检测到" + lvPortResult.Items.Count.ToString() + "个端口！";
            }
            else
            {
                string startIp = txtPortStart.Text.Trim();
                string endIp = txtPortEnd.Text.Trim();

                int threadCount = Convert.ToInt32(cboxPortThread.Text);
                int timeOut = Convert.ToInt32(cboxPortTimeOut.Text);

                string[] ports = txtPortPorts.Text.Contains(",") ? txtPortPorts.Text.Trim().Split(',') : new string[] { txtPortPorts.Text.Trim() };

                SortedList<string,VarFile> slGetPass=null;
                slPortIndex.Clear();

                if (chkPortGetPassFTP.Checked || chkPortGetPassMysql.Checked || chkPortGetPassRemote.Checked || chkPortGetPassSMB.Checked || chkPortGetPassSqlServer.Checked || chkPortGetPassSSH.Checked)
                {
                    slGetPass = new SortedList<string, VarFile>();
                    VarFile varFile;
                    if (chkPortGetPassFTP.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassFTPUser.Text, "user");
                        varFile.AddVar(txtPortGetPassFTPPass.Text, "pass");
                        slGetPass.Add("ftp", varFile);
                    }
                    if (chkPortGetPassMysql.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassMySqlUser.Text, "user");
                        varFile.AddVar(txtPortGetPassMySqlPass.Text, "pass");
                        slGetPass.Add("mysql", varFile);
                    }
                    if (chkPortGetPassRemote.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassRemoteUser.Text, "user");
                        varFile.AddVar(txtPortGetPassRemotePass.Text, "pass");
                        slGetPass.Add("remote", varFile);
                    }
                    if (chkPortGetPassSMB.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassSMBUser.Text, "user");
                        varFile.AddVar(txtPortGetPassSMBPass.Text, "pass");
                        slGetPass.Add("smb", varFile);
                    }
                    if (chkPortGetPassSqlServer.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassSqlServerUser.Text, "user");
                        varFile.AddVar(txtPortGetPassSqlServerPass.Text, "pass");
                        slGetPass.Add("sqlserver", varFile);
                    }
                    if (chkPortGetPassSSH.Checked)
                    {
                        varFile = new VarFile();
                        varFile.AddVar(txtPortGetPassSSHUser.Text, "user");
                        varFile.AddVar(txtPortGetPassSSHPass.Text, "pass");
                        slGetPass.Add("ssh", varFile);
                    }
                }

                if (lvPortResult.Items.Count > 0)
                {
                    if (MessageBox.Show("是否清空搜索结果？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        lvPortResult.Items.Clear();
                }

                pbar.Value = 0;
                pbar.Maximum = 0;
                GetPassHelper.TimeOut = Convert.ToInt32(cboxPortLogin.Text);
                if (!portScan.Start(slGetPass,threadCount, timeOut, startIp, endIp, ports))
                {
                    labState.Text = portScan.Error;
                    MessageBox.Show(portScan.Error, "开启失败");
                    return;
                }

                pbar.Maximum = portScan.TotalCount;
                labState.Text = "正在扫描...";
                timerPort.Enabled = true;
                btnPortStart.Text = "停止扫描";

                labTotalTarget.Text = "检测总数：" + portScan.TotalCount.ToString();
            }

        }

        private void PortScan_ScanFoundPortEvent(string ip, int port,string mark="")
        {
            lvPortResult.BeginInvoke((Action)delegate
            {
                try
                {
                    string id=ip+":"+port.ToString();
                    if (slPortIndex.ContainsKey(id))
                    {
                        lvPortResult.Items[slPortIndex[id]].SubItems[3].Text = mark;
                    }
                    else
                    {
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = (lvPortResult.Items.Count + 1).ToString();
                        lvi.SubItems.Add(ip);
                        lvi.SubItems.Add(port.ToString());
                        lvi.SubItems.Add(mark);

                        lock (objPortLocker)
                        {
                            slPortIndex.Add(ip + ":" + port, lvPortResult.Items.Count);
                            lvPortResult.Items.Add(lvi);
                        }
                    }
                    //lvPortResult.Items[lvPortResult.Items.Count - 1].EnsureVisible();
                    labState.Text = "发现端口：" + ip + ":" + port.ToString() + "  " + mark;
                    Application.DoEvents();
                }
                catch { }

            });
        }

        private void PortScan_ScanCompleteEvent()
        {
            try
            {
                this.BeginInvoke((Action)delegate
                {
                    timerPort.Enabled = false;
                    btnPortStart.Text = "开始扫描";
                    pbar.Value = pbar.Maximum;
                    labExpect.Text = "共计耗时：" + portScan.SpandTime;
                    labSpeed.Text = "平均速度：" + portScan.AvgSpeed.ToString() + "/s";
                    labState.Text = "扫描结束，共检测到" + portScan.SuccCount.ToString() + "个结果！";
                    MessageBox.Show("扫描结束，共检测到" + portScan.SuccCount.ToString() + "个结果！", "扫描完成");
                });
            }
            catch { }
        }

        private void PortScan_ScaningTestPassEvent(string ip, int port, string mark)
        {
            this.BeginInvoke((Action)delegate {
                string id=ip+":"+port.ToString();
                if (slPortIndex.ContainsKey(id))
                {
                    lvPortResult.Items[slPortIndex[id]].SubItems[3].Text = mark;
                }
                else
                    labState.Text =id+ "  " + mark;
                Application.DoEvents();
            });

            //lvPortResult.BeginInvoke((Action)delegate
            //{
            //    string id = ip + ":" + port;
            //    if (slPortIndex.ContainsKey(id))
            //    {
            //        lvPortResult.Items[slPortIndex[id]].SubItems[3].Text = mark;
            //        Application.DoEvents();
            //    }
            //});
        }

        private void timerPort_Tick(object sender, EventArgs e)
        {
            pbar.Value = portScan.PassCount;
            labSpeed.Text = "扫描速度：" + portScan.Speed.ToString() + "/s";
            labExpect.Text = "剩余：" + portScan.ExpectComplete;
        }

        private void txtPortStart_Leave(object sender, EventArgs e)
        {
            if(txtPortEnd.Text.Length==0 || (txtPortStart.Text.Split('.')[0] !=txtPortEnd.Text.Split('.')[0]))
                txtPortEnd.Text = txtPortStart.Text.Trim();
        }

        private void btnPortClear_Click(object sender, EventArgs e)
        {
            lvPortResult.Items.Clear();
        }
        
        private void lvPortResult_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button!=MouseButtons.Right || lvPortResult.SelectedItems.Count == 0)
                return;

            menuPort.Show(Cursor.Position);
        }

        private void btnPortOpenWeb_Click(object sender, EventArgs e)
        {
            string ip = lvPortResult.SelectedItems[0].SubItems[1].Text + ":" + lvPortResult.SelectedItems[0].SubItems[2].Text;
            new FrmWebLook("http://" + ip).Show();
        }

        private void btnPortCopy_Click(object sender, EventArgs e)
        {
            ListViewItem lvi= lvPortResult.SelectedItems[0];
            string ip = lvi.SubItems[1].Text ;
            ClipboardHelper.SetText(ip);
        }

        private void btnPortOpenBrower_Click(object sender, EventArgs e)
        {
            string ip = "http://" + lvPortResult.SelectedItems[0].SubItems[1].Text + ":" + lvPortResult.SelectedItems[0].SubItems[2].Text;
            ProcessHelper.OpenUrl(ip);
        }

        private void btnPortTelnet_Click(object sender, EventArgs e)
        {
            string ip = lvPortResult.SelectedItems[0].SubItems[1].Text + " " + lvPortResult.SelectedItems[0].SubItems[2].Text;
            ProcessHelper.OpenCmd("telnet " +  ip);
        }

        private void lvPortResult_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lvPortResult.SelectedItems.Count == 0)
                return;

            string ip = "http://" + lvPortResult.SelectedItems[0].SubItems[1].Text + ":" + lvPortResult.SelectedItems[0].SubItems[2].Text;
            new FrmWebLook(ip).Show();
        }

        private void btnPortWebScan_Click(object sender, EventArgs e)
        {
            string ip = "http://" + lvPortResult.SelectedItems[0].SubItems[1].Text + ":" + lvPortResult.SelectedItems[0].SubItems[2].Text;

            txtWebSite.Text = ip;
            tabMain.SelectedIndex = 0;
        }

        private void btnPortCopyTotal_Click(object sender, EventArgs e)
        {
            string ips = "";
            foreach (ListViewItem lvi in lvPortResult.Items)
            {
                ips += lvi.SubItems[1].Text + ":" + lvi.SubItems[2].Text + "," + lvi.SubItems[3].Text +"\r\n";
            }

            ClipboardHelper.SetText(ips);
        }

        private void btnPortOutputFile_Click(object sender, EventArgs e)
        {
            string ips = "";
            foreach (ListViewItem lvi in lvPortResult.Items)
            {
                ips += lvi.SubItems[1].Text + ":" + lvi.SubItems[2].Text + "\r\n";
            }
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "文本文件(*.txt)|*.txt";
            if (sf.ShowDialog() != DialogResult.OK)
                return;

            try
            {
                File.WriteAllText(sf.FileName,ips);
                MessageBox.Show("保存路径：" + sf.FileName, "保存成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show( ex.Message, "保存失败");
            }
        }

        private void btnPortCopyLine_Click(object sender, EventArgs e)
        {
            string ip = "";

            foreach (ListViewItem lvi in lvPortResult.SelectedItems)
            {
                ip += lvi.SubItems[1].Text + " " + lvi.SubItems[2].Text + " " + lvi.SubItems[3].Text + "\r\n";
            }
            ClipboardHelper.SetText(ip);
        }

        private void Port_SelectFile(TextBox txt)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件（*.txt）|*.txt";
            if (of.ShowDialog() != DialogResult.OK)
                return;

            string file = of.FileName.Replace(SysHelper.AppPath, "");
            txt.Text = file;
        }

        private void btnPortGetPassUserFile_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassFTPUser);
        }

        private void btnPortGetPassUserPass_Click(object sender, EventArgs e)
        {

            Port_SelectFile(txtPortGetPassFTPUser);
        }

        private void btnPortGetPassUserFileSSH_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSSHUser);
        }

        private void btnPortGetPassPassFileSSH_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSSHPass);
        }

        private void btnPortGetPassUserFileSqlServer_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSqlServerUser);
        }

        private void btnPortGetPassPassFileSqlServer_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSqlServerPass);
        }

        private void btnPortGetPassUserFileMySql_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassMySqlUser);
        }

        private void btnPortGetPassPassFileMySql_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassMySqlPass);
        }

        private void btnPortGetPassUserFileRDP_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassRemoteUser);
        }

        private void btnPortGetPassPassFileRDP_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassRemotePass);
        }

        private void btnPortGetPassUserFileSMB_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSMBUser);
        }

        private void btnPortGetPassPassFileSMB_Click(object sender, EventArgs e)
        {
            Port_SelectFile(txtPortGetPassSMBPass);
        }

        private void chkPortGetPassAll_CheckedChanged(object sender, EventArgs e)
        {
            chkPortGetPassFTP.Checked = chkPortGetPassAll.Checked;
            chkPortGetPassSSH.Checked = chkPortGetPassAll.Checked;
            //chkPortGetPassSMB.Checked = chkPortGetPassAll.Checked;
            chkPortGetPassSqlServer.Checked = chkPortGetPassAll.Checked;
            chkPortGetPassMysql.Checked = chkPortGetPassAll.Checked;
            //chkPortGetPassRemote.Checked = chkPortGetPassAll.Checked;
        }

        private void btnPortCopyIPPORT_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            string ip = lvi.SubItems[1].Text + " " + lvi.SubItems[2].Text;
            ClipboardHelper.SetText(ip);
        }

        private void btnPortGetPassMySqlFast_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("mysql", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_40.txt");
        }

        private void btnPortGetPassMySqlNormal_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("mysql", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_200.txt");
        }

        private void btnPortGetPassMySqlAll_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("mysql", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_2000.txt");
        }

        private void Port_Scan(string method, string ip, string port, string passfile)
        {
            portScan.Stop();

            string startIp = ip;
            string endIp = ip;

            int threadCount = Convert.ToInt32(cboxPortThread.Text);
            int timeOut = Convert.ToInt32(cboxPortTimeOut.Text);

            string[] ports = new string[] { port };

            SortedList<string, VarFile> slGetPass = new SortedList<string, VarFile>();
            VarFile varFile;
            if (method == "ftp")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassFTPUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("ftp", varFile);
            }
            else if (method == "mysql")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassMySqlUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("mysql", varFile);
            }
            else if (method == "remote")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassRemoteUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("remote", varFile);
            }
            else if (method == "smb")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassSMBUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("smb", varFile);
            }
            else if (method == "sqlserver")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassSqlServerUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("sqlserver", varFile);
            }
            else if (method == "ssh")
            {
                varFile = new VarFile();
                varFile.AddVar(txtPortGetPassSSHUser.Text, "user");
                varFile.AddVar(passfile, "pass");
                slGetPass.Add("ssh", varFile);
            }

            pbar.Value = 0;
            pbar.Maximum = 0;
            GetPassHelper.TimeOut = Convert.ToInt32(cboxPortLogin.Text);
            if (!portScan.Start(slGetPass, threadCount, timeOut, startIp, endIp, ports, method))
            {
                labState.Text = portScan.Error;
                MessageBox.Show(portScan.Error, "开启失败");
                return;
            }

            pbar.Maximum = portScan.TotalCount;
            labState.Text = "正在扫描...";
            timerPort.Enabled = true;
            btnPortStart.Text = "停止扫描";

            labTotalTarget.Text = "检测总数：" + portScan.TotalCount.ToString();

        }


        private void btnPortGetPassSqlserverFast_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("sqlserver", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_40.txt");
        }

        private void btnPortGetPassSqlserverNormal_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("sqlserver", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_200.txt");
        }

        private void btnPortGetPassSqlserverAll_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = lvPortResult.SelectedItems[0];
            Port_Scan("sqlserver", lvi.SubItems[1].Text, lvi.SubItems[2].Text, "pass_2000.txt");
        }

        #endregion

        #region HTTP
        private void Http_Init()
        {
            for (int i = 1; i <= 100; i++)
            {
                cboxHttpThread.Items.Add(i.ToString());
            }

            for (int i = 100; i <= 10000; i+=100)
            {
                cboxHttpTimeOut.Items.Add(i.ToString());
            }

            Config.Get(cboxHttpThread,"20");
            Config.Get(cboxHttpTimeOut, "1000");

            Config.Get(cboxHttpMethod,"GET");
            Config.Get(cboxHttpEncoding,"UTF8");
            
            Config.Get(rdHttpInclude);
            rdHttpUnclude.Checked = !rdHttpInclude.Checked;

            Config.Get(txtHttpInclude);
            Config.Get(txtHttpUnclude);

            Config.Get(txtHttpUrl);
            Config.Get(txtHttpData);

            Config.Get(chkHttpStopAuto);
        }

        private void HttpScan_FoundVarEvent(string url, string data, string header)
        {
            txtHttpResponse.BeginInvoke((Action)delegate{
                string line=string.Format("--------返回数据匹配成功 时间：{0}---------\r\n【请求URL】{1}\r\n【发送数据】{2}\r\n【请求头】{3}\r\n\r\n"
                    ,DateTime.Now.ToString()
                    ,url,data,header);

                txtHttpResponse.AppendText(line);
                labState.Text = "探测到匹配数据！";
                Application.DoEvents();

            });
        }

        private void HttpScan_ScanCompleteEvent()
        {
            this.BeginInvoke((Action)delegate {
                timerHttp.Enabled = false;
                pbar.Value = pbar.Maximum;
                labExpect.Text = "共计耗时："+httpScan.SpandTime;
                labSpeed.Text = "平均速度：" + httpScan.AvgSpeed.ToString()+"/s";
                btnHttpStart.Text = "穷举探测";
                labState.Text = "穷举完成，共扫描到" + httpScan.SuccCount.ToString() + "个结果！";
                MessageBox.Show("穷举探测完成！" +DateTime.Now.ToString(), "完成");
            });

        }

        private void btnHttpRequest_Click(object sender, EventArgs e)
        {
            txtHttpResponse.Text = "";
            gboxHttp.Text = "正在请求...";
            Application.DoEvents();

            Encoding encoding = cboxHttpEncoding.Text=="UTF8" ? Encoding.UTF8 : Encoding.Default;
            string method = cboxHttpMethod.Text.ToUpper();
            string url = txtHttpUrl.Text.Trim();
            string header = txtHttpHeader.Text.Trim();
            string data = txtHttpData.Text;
            string ret = HttpSocketHelper.Request(method,url, data, header, encoding);

            gboxHttp.Text = "返回数据：" + DateTime.Now.ToString();
            txtHttpResponse.Text = ret;

            labTotalTarget.Text = "单次请求";


        }

        private void btnHttpStart_Click(object sender, EventArgs e)
        {

            if (btnHttpStart.Text == "停止探测")
            {
                httpScan.Stop();
                timerHttp.Enabled = false;
                btnHttpStart.Text = "开始探测";
            }
            else
            {
                Encoding encoding = cboxHttpEncoding.SelectedIndex == 0 ? Encoding.UTF8 : Encoding.Default;
                string method = cboxHttpMethod.SelectedIndex == 0 ? "GET" : "POST";
                string url = txtHttpUrl.Text.Trim();
                string header = txtHttpHeader.Text.Trim();
                string data = txtHttpData.Text;
                int threadCount = Convert.ToInt32(cboxHttpThread.Text);
                int timeOut = Convert.ToInt32(cboxHttpTimeOut.Text);
                bool isInclude = rdHttpInclude.Checked;
                string[] include = txtHttpInclude.Lines;
                string[] unclude = txtHttpUnclude.Lines;
                bool isStopauto = chkHttpStopAuto.Checked;
         

                txtHttpResponse.Text="";
                
                if(varHttp!=null)
                    varHttp.Clear();


                if (!varHttp.AddMatch(data))
                {
                    MessageBox.Show(varHttp.Error, "提示");
                    return;
                }

                if (!varHttp.AddMatch(url))
                {
                    MessageBox.Show(varHttp.Error, "提示");
                    return;
                }

                if (!varHttp.AddMatch(header))
                {
                    MessageBox.Show(varHttp.Error, "提示");
                    return;
                }

                if (varHttp.Count == 0)
                {
                    labState.Text = "当前网址URL、GET/POST数据参数、请求头中均不包含变量关键词！";
                    MessageBox.Show("当前网址URL、GET/POST数据参数、请求头中均不包含变量关键词，请先在参数中增加，格式如下：\r\n读取文本：{%pass.txt%}、{%d:\\用户名.txt%}\r\n数组形式：{%x1,x2%}、{%admin,admin1,user1%}", "提示");
                    return;
                }

                pbar.Value = 0;
                pbar.Maximum = varHttp.TotalCount;


                bool ret = httpScan.Start(varHttp,isStopauto,threadCount, timeOut, method, url, data, header, encoding, isInclude, include, unclude);
                if (ret)
                {
                    btnHttpStart.Text = "停止探测";
                    labState.Text = "正在探测，需探测" + httpScan.TotalCount.ToString()+"次！";
                }
                timerHttp.Enabled = true;

                labTotalTarget.Text = "检测总数："+httpScan.TotalCount.ToString();
            }

        }

        private void btnHttpHeaderCopy_Click(object sender, EventArgs e)
        {
            ClipboardHelper.SetText(txtHttpHeader.Text);
        }

        private void btnHttpHeaderPaste_Click(object sender, EventArgs e)
        {
            txtHttpHeader.Text = Clipboard.GetText();
        }

        private void btnHttpHeaderClear_Click(object sender, EventArgs e)
        {
            txtHttpHeader.Text = "";
        }

        private void btnHttpHeaderNormal_Click(object sender, EventArgs e)
        {
            txtHttpHeader.Text = "User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";

        }

        private void btnHttpHeaderMore_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\r\n");
            sb.Append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n");
            sb.Append("Content-Type: text/html\r\n");
            sb.Append("Cookie: \r\n");
            sb.Append("Referer: \r\n");

            txtHttpHeader.Text = sb.ToString();

        }

        private void timerHttp_Tick(object sender, EventArgs e)
        {
            pbar.Value = httpScan.PassCount;
            labSpeed.Text = "扫描速度：" + httpScan.Speed.ToString() + "/s";
            labExpect.Text = "剩余时间：" + httpScan.ExpectComplete;
        }

        #endregion

        #region Tool

        private void Tool_Init()
        {
            txtToolDomain.Text = Config.Get("txtToolDomain");
            txtToolDomainIP.Text = Config.Get("txtToolDomainIP");

        }

        private void btnToolDomain_Click(object sender, EventArgs e)
        {

            txtToolDomainIP.Text = ""; 
            try
            {

                IPAddress[] ips = Dns.GetHostAddresses(txtToolDomain.Text);
                txtToolDomainIP.Text = ips[0].ToString();
            }
            catch 
            {
                txtToolDomainIP.Text = "未找到";
            }
        }

        #endregion



 





   




    }
}
